package com.example.system.manager;

import com.example.common.core.constants.CacheConstants;
import com.example.common.redis.service.RedisService;
import com.example.system.domain.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {
    @Autowired
    private RedisService redisService;


    public void refreshUser(User user) {
        //刷新用户缓存
        String userKey = getUserKey(user.getUserId());
        User redisUser = redisService.getCacheObject(userKey, User.class);
        if (redisUser == null) {
            return;
        }
        redisService.setCacheObject(userKey, user);
        //设置用户缓存有效期为10分钟
        redisService.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }

    //u:d:用户id
    private String getUserKey(Long userId) {
        return CacheConstants.USER_DETAIL + userId;
    }

    public boolean removeUserById(Long userId) {
        String LoginTokenKey = getLoginTokenKey(userId);
        return redisService.deleteObject(LoginTokenKey);
    }

    private String getLoginTokenKey(Long userId) {
        return CacheConstants.LOGIN_TOKEN_KEY + userId;
    }
}
